package com.start.security;

import com.start.common.configs.StartTokenConfig;
import com.start.common.details.BaseUserDetails;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;


@Component
public class StartTokenAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private StartTokenConfig tokenConfig;

    @Autowired
    private StartTokenTools startTokenTools;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String authHeader = request.getHeader(tokenConfig.getTokenKey());
        if (StringUtils.isEmpty(authHeader)) {
            nextFilter(request, response, chain);
            return;
        }
        if (!authHeader.startsWith(tokenConfig.getTokenValuePrefix())) {
            nextFilter(request, response, chain);
            return;
        }
        String token = authHeader.substring(tokenConfig.getTokenValuePrefix().length());
        if (StringUtils.isEmpty(token)) {
            nextFilter(request, response, chain);
            return;
        }
        if (!startTokenTools.hasToken(token)) {
            nextFilter(request, response, chain);
            return;
        }
        BaseUserDetails baseUserDetails = startTokenTools.getUserDetailsByToken(token);
        if (baseUserDetails == null) {
            nextFilter(request, response, chain);
            return;
        }
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(baseUserDetails, null, baseUserDetails.getAuthorities());
        authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        nextFilter(request, response, chain);
    }

    private void nextFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        chain.doFilter(request, response);
    }


}
